package com.terry.gamehall.gms.exception;

import com.terry.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.Binding;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.terry.gamehall.gms.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        Map<String,String> map = new HashMap<>();
        BindingResult result = e.getBindingResult();
        //获取校验的错误结果
        result.getFieldErrors().forEach((item)->{
            //FieldError 获取到错误提示
            String message =  item.getDefaultMessage();
            //获取到错误的属性名字
            String field = item.getField();
            map.put(field,message);
        });
        return R.error(400,"提交的数据不合法!").put("data",map);
    }
}
